package com.yx.cloud.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.iot.base.service.req.DataParam;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.FirmwareUpdateInfo;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.bean.RobotStatus;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.CleanSettingParam;
import com.yx.cloud.R;
import com.yx.cloud.activity.FirmwareUpgradeActivity;
import com.yx.cloud.activity.GyroFirmwareUpgradeActivity;
import com.yx.cloud.activity.MainActivity2;
import com.yx.cloud.base.LazyLoadFragment;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.product.gyro.N5Config;
import com.yx.cloud.product.laser.yxcloud.X3CloudConfig;
import com.yx.cloud.product.laser.yxcloud.X5_MAX;
import com.yx.cloud.utils.AnimationtUtils;
import com.yx.cloud.utils.AppUtil;
import com.yx.cloud.utils.DisplayUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.view.BatteryViewStatic;
import com.yx.cloud.view.BottomLayoutView;
import com.yx.cloud.view.LightAnimationUtils;
import com.yx.cloud.view.SetTextImageShow;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

public class MainFragment extends LazyLoadFragment implements GestureDetector.OnGestureListener, View.OnTouchListener {
    private final static String TAG = "MainFragment";
    private static MainActivity2 activity;
    public BatteryViewStatic mBatteryView;
    public ImageView mIvMianFramengIcon, mAnimateSideBrush, mAnimateSideBrushRight,
            mIvChargringIcon, mStateAnimation, ivSwitchRobotIcon, ivCustomerServiceIcon;
    public RotateAnimation rotate;
    public TextView tvMainSweepTime, tvMainSweepArea, mTvSweepState, mTvElseState, mUpgradeDesc;
    public RelativeLayout mRlMainStateBg, mRlMainFragment, mFirmwareUpdateLayout, rlBottomLayoutViewBg;
    public LinearLayout mRlFragmentBattery, mOfflineLayout, mLLSweepState;
    public Robot robot;
    public Button mUpdate_Now;
    private TextView mTvEquipmentSeriesName, mTvPower, tvAreaUnit;
    private CheckBox mCbCleanMop;
    private String deviceName, dustSingState = "0", mWorkingStatus = "", mButStatus = "", errorStr = "";
    private boolean mIsOnLine = false, mSing = false;
    private int mRechargeIcon = 0, mCleanIcon = 0, mBattery = 100, CurrentMode = 1000, CurrentState = 1000, fault_error = 0;
    private Dialog dialog;
    private JSONObject productConfig;
    private int currentItem;
    private int firmwareNumber = 0;
    private int equipmentType;
    private VelocityTracker mVelocityTracker;
    private float ee1 = 0, ee2 = 0, yVelocity;
    private int regFrom, startX, criticalValue = 50;
    public LinearLayout mainGuideLayout01, mainGuideLayout03, mainGuideLayout04;
    public RelativeLayout mainGuideLayout02;
    public Dialog guideDialog;
    public BottomLayoutView bottomLayoutView;
    private static final int FLING_MIN_DISTANCE = 50;
    private static final int FLING_MIN_DISTANCE_TOUCH = 350;
    private static final int FLING_MIN_VELOCITY = 0;
    public GestureDetector mGestureDetector;
    private boolean stateTransform;

    public MainFragment() {
        super();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected int setContentView() {
        return R.layout.main_frameng;
    }

    public static MainFragment newInstance(Bundle args) {
        MainFragment f = new MainFragment();
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        activity = (MainActivity2) getActivity();
        robot = AppContext.get().getCurrentDevice();
        initView();
        initData();
        return view;
    }

    private void initView() {
        LogUtils.i("initView***************  ");
        mBatteryView = findViewById(R.id.batteryView);
        mIvMianFramengIcon = findViewById(R.id.iv_mianFrameng_icon);
        mTvEquipmentSeriesName = findViewById(R.id.tv_equipmentSeriesName);
        mTvPower = findViewById(R.id.tv_power);
        tvMainSweepTime = findViewById(R.id.tv_sweepTime);
        tvMainSweepArea = findViewById(R.id.tv_sweepArea);
        mTvSweepState = findViewById(R.id.tv_sweepState);
        mLLSweepState = findViewById(R.id.ll_sweepState);
        mTvElseState = findViewById(R.id.tv_elseState);
        mRlMainStateBg = findViewById(R.id.rl_main_stateBg);
        mAnimateSideBrush = findViewById(R.id.animateSideBrush);
        mAnimateSideBrushRight = findViewById(R.id.animateSideBrush_right);
        mStateAnimation = findViewById(R.id.stateAnimation);
        mRlFragmentBattery = findViewById(R.id.rl_fragmentBattery);
        mIvChargringIcon = findViewById(R.id.iv_chargringIcon);
        mRlMainFragment = findViewById(R.id.rl_mainFragment);
        mCbCleanMop = findViewById(R.id.cb_cleanMop);
        mOfflineLayout = findViewById(R.id.offline_layout);
        mFirmwareUpdateLayout = findViewById(R.id.firmwareUpdate_layout);
        mUpgradeDesc = findViewById(R.id.main_upgradeDesc);
        mUpdate_Now = findViewById(R.id.main_update_Now);
        ivSwitchRobotIcon = findViewById(R.id.iv_mainSwitchRobot_Icon);
        ivCustomerServiceIcon = findViewById(R.id.iv_customerServiceIcon);
        bottomLayoutView = findViewById(R.id.bottom_layoutView);
        rlBottomLayoutViewBg = findViewById(R.id.rl_bottom_layoutViewBg);
        tvAreaUnit = findViewById(R.id.tv_AreaUnit);
        /***
         * 清扫拖布/停止清扫拖布
         */
        mCbCleanMop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!buttonView.isPressed()) {
                    return;
                }
                if (isChecked) {
                    mCbCleanMop.setText(getString(R.string.BS_CleanMop_Cancel));
                } else {
                    mCbCleanMop.setText(getString(R.string.BS_CleanMop_Start));
                }
                Log.d(TAG, "清扫拖布***************  " + isChecked);
                AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().cleanMop(isChecked).build());
            }
        });

        mUpdate_Now.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                AppContext.getProductService().updateFirmware();//获取升级状态
                if (mUpdate_Now.getText().toString().equals(getString(R.string.U_Update))) {
                    if (!productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmware)) {
                        return;
                    }
                    if (productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmwareChannel)) {
                        Intent_utils.enterIntentContext(activity, GyroFirmwareUpgradeActivity.class, "type", "Update_Now");
                    } else {
                        Intent_utils.enterIntentContext(activity, FirmwareUpgradeActivity.class, "type", "Update_Now");
                    }

                } else if (mUpdate_Now.getText().toString().equals(getString(R.string.O_Update_Btn))) {
                    if (productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmwareChannel)) {
                        Intent_utils.enterIntentContext(activity, GyroFirmwareUpgradeActivity.class, "type", "show_update_state");
                    } else {
                        Intent_utils.enterIntentContext(activity, FirmwareUpgradeActivity.class, "type", "show_update_state");
                    }
                }
            }
        });

        ivSwitchRobotIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //切换机器图片 TODO
                activity.switchRobotIcon(mIvMianFramengIcon);
            }
        });
        ivCustomerServiceIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean wxPk = AppUtil.isPkgInstalled(activity, "com.tencent.mm");
                if (wxPk) {
                    Intent_utils.gotoShop(activity, "http://isemall.cn/efYNZv2aC");
                } else {
                    Toast.makeText(activity, getString(R.string.install_WeChat), Toast.LENGTH_LONG).show();
                }
            }
        });

        bottomLayoutView.mCbMainBottomUnfold.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!buttonView.isPressed()) {
                    return;
                }
                Log.d(TAG, " : mCBMainUnfold********** : " + isChecked);
                if (!isChecked) {
                    if (bottomLayoutView.bun_time_water != null) {
                        //点击吸力水量 开始倒计时终止
                        bottomLayoutView.bun_time_water.cancel();
                        bottomLayoutView.recoverWaterBtn();//恢复吸力水量 按钮的状态
                    }
                    if (bottomLayoutView.bun_time_sucion != null) {
                        //点击吸力水量 开始倒计时终止
                        bottomLayoutView.bun_time_sucion.cancel();
                        bottomLayoutView.recoverSuctionBtn();//恢复吸力水量 按钮的状态
                    }
                    activity.binding.rlMain.setBackgroundResource(R.color.background_color);
                    //有底部导航
                    activity.setBottomUiState("close", true, "66");
                    bottomLayoutView.mCbMainBottomUnfold.setChecked(false);
                } else {
                    activity.setBottomUiState("open", false, "open 111");
                    bottomLayoutView.mCbMainBottomUnfold.setChecked(true);
                }
            }
        });

        if (!X5_MAX.PID.equals(robot.getProductId())) {
            activity.binding.ivRightMenu.setVisibility(View.VISIBLE);//右侧菜单
            setGuideInterface("bbb");
        }

    }

    private void initData() {
        mGestureDetector = new GestureDetector(this);
        bottomLayoutView.setOnTouchListener(this);
        bottomLayoutView.setFocusable(true);
        bottomLayoutView.setClickable(true);
        bottomLayoutView.setLongClickable(true);

        firmwareNumber = 0;
        CurrentMode = 1000;
        CurrentState = 1000;
        mBattery = 100;
        fault_error = 0;
        Constants.click_location = "";
        mRlMainStateBg.setVisibility(View.VISIBLE);
        //切换设备时，先清空错误信息
        activity.mMesListData.clear();
        activity.binding.mainMesList.setVisibility(View.GONE);//消息列表
        LogUtils.i(Constants.ITEM_POSITION + " : initData***************  " + currentItem);

        setRobotMessage(currentItem);


    }

    @Override
    public void onPageSelect(int position) {
        super.onPageSelect(position);
        LogUtils.i(position + " ====onPageSelect =========================================== ");
        activity.binding.ivRightMenu.setVisibility(View.VISIBLE);//右侧菜单

        initializationData("111");
        if (robot.isOnline()) {
            setGuideInterface("aaa");
        }
    }

    @Override
    public void onPageUnselect(int position) {
        super.onPageUnselect(position);
    }

    /***
     * 设置机器信息
     *
     * @param position
     */
    public void setRobotMessage(int position) {
        initializationData("000");
    }

    public void initializationData(String source) {
        LogUtils.i(" ==== initializationData =========== " + source);
        CurrentMode = 1000;
        CurrentState = 1000;
        mBattery = 100;
        fault_error = 0;
        errorStr = "";
        //切换设备是保存当前设备ID，用于inxni的机器图标切换
        productConfig = AppContext.getConfig();
        //INXNI 切换机器图片
        DisplayUtil.show(ivSwitchRobotIcon, productConfig.optBoolean(ProductConfigConstants.hasMultiStyle));
        //客服跳转图标
        DisplayUtil.show(ivCustomerServiceIcon, productConfig.optBoolean(ProductConfigConstants.customerService));
        //设备名称
        deviceName = robot.getName();
        mTvEquipmentSeriesName.setText(deviceName);
        LogUtils.i(deviceName + " , " + robot.getDeviceId() + " ====robot.getDeviceId() =========== " + robot.getProductId());
        // 根据pid判断机器型号，进行分类显示不同的机型图片
        mIvMianFramengIcon.setImageResource(productConfig.optInt(ProductConfigConstants.robot_Airview));
        mAnimateSideBrush.setVisibility(View.VISIBLE);//边刷
        DisplayUtil.show(mAnimateSideBrushRight, productConfig.optBoolean(ProductConfigConstants.rightSideBrush));//右侧边刷
        mIsOnLine = robot.isOnline();

        LogUtils.i(source + " :  ===静态=是否在线 =========== " + mIsOnLine);
        //判断设备是否在线
        deviceIsOnLine(mIsOnLine, source);
    }

    /***
     * 判断设备是否在线
     */
    private void deviceIsOnLine(boolean isOnline, String source) {
        if (isOnline) {
            //操作引导界面
            CurrentState = 1000;
            CurrentMode = 1000;
            //设备名称
            mRlFragmentBattery.setVisibility(View.VISIBLE);
            mFirmwareUpdateLayout.setVisibility(View.GONE);//升级布局
            mOfflineLayout.setVisibility(View.GONE);//离线布局
            activity.setBottomUiState("close", true, "88");
            if (productConfig.optBoolean(ProductConfigConstants.hasWashMop)) {
                mCbCleanMop.setVisibility(View.VISIBLE);//是否显示主界面的清扫拖布按钮
                mCbCleanMop.setChecked(robot.getCleanSettings().isCleanMop());
            } else {
                mCbCleanMop.setVisibility(View.GONE);
            }

            if (productConfig.optBoolean(ProductConfigConstants.hasMap)) {
                activity.isShowMapRead(robot);//发现新地图提示
            }
            bottomLayoutView.initializationData("static_open", "open");//

            if (!robot.isShare() && robot.isOnline()) {
                LogUtils.i(" ====固件更新检测了：" + robot.getFirmwareUpdateInfo().isCheck() + " , State : " + robot.getFirmwareUpdateInfo().getUpgradeStatus());
                if (!robot.getFirmwareUpdateInfo().isCheck()) {
                    //  LogUtils.i(" ====固件更新检测了 22222 =========== " + AppContext.get().isInterfaceIsSlide());
                    //切换设备进行，检测新版本
                    DataParam param = new DataParam();
                    param.setData_type("upgrade_package");
                    AppContext.getProductService().getDataList(param);
                } else {
                    int state = robot.getFirmwareUpdateInfo().getState();
//                    if (state == 2) {
//                        //强制升级
//                        if (activity.firmware_dialog != null) {
//                            if (activity.firmware_dialog.isShowing()) {
//                                activity.firmware_dialog.dismiss();//关闭估计新版本弹框
//                            }
//                        }
//                        forceUpgradeTips();//强制升级提示布局
//                    } else
                    if (state == 1 || state == 2 || state == 3) {
                        //升级中
                        if (activity.firmware_dialog != null) {
                            if (activity.firmware_dialog.isShowing()) {
                                activity.firmware_dialog.dismiss();//关闭估计新版本弹框
                            }
                        }
                        ViewUpgradeTips();//查看升级状态提示布局
                    }
                }
            }

            setLookMapUiShowManage();
            //如果检测过就不检测了
            if (activity.firmware_dialog != null) {
                activity.firmware_dialog.dismiss();
            }
            stateShow();
        } else {
            offLineState();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
//        LogUtils.i(robot.getDeviceId() + " event mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm");
        if (productConfig.optBoolean(ProductConfigConstants.cleaning_unit_area)) {
            int unitSettings = robot.getCleanSettings().getUnitSettings();
            if (1 == unitSettings) {
                //平方英尺 平方米转换
                tvAreaUnit.setText("ft²");
            } else {
                tvAreaUnit.setText("m²");
            }
        } else {
            tvAreaUnit.setText("m²");
        }
        switch (event.getType()) {
            case Event.MSG_ROBOT_STATE:
                //状态上报
                int firmwareState_msg = robot.getFirmwareUpdateInfo().getState();
                LogUtils.i(mIsOnLine + " :   状态上报：：：：：：：：：：：：: 固件 ；" + firmwareState_msg);
                if (firmwareState_msg == 3) {
                } else {
                    stateShow();
                }
                break;
            case Event.MESSAGE_TYPE_CLEAN_AREA_DURATION:
                //清扫时间，面积上报， 显示设置中间显示的（状态，清扫时间，清扫面积）
                LogUtils.i(" 清扫时间 面积上报 :" + robot.getCleanStatistics().getCleanTime() + " , " + robot.getCleanStatistics().getCleanArea());
                if (!mIsOnLine) {
                    //如果设备离线或者正在滑动界面
                    return;
                }
                int cleanTime = this.robot.getCleanStatistics().getCleanTime();
                if (!productConfig.optBoolean(ProductConfigConstants.showCleanArea)) {
                    //清扫时长/清扫面积/当前状态文字
                    SetTextImageShow.setText(tvMainSweepTime, cleanTime + "", tvMainSweepArea, "--");
                } else {
                    int cleanArea = (int) this.robot.getCleanStatistics().getCleanArea();
                    //清扫时长/清扫面积/当前状态文字
                    SetTextImageShow.setText(tvMainSweepTime, cleanTime + "", tvMainSweepArea, cleanArea + "");
                }
                break;
            case Event.MESSAGE_TYPE_WATER_STATUS:
                //水量
                int firmwareState_water = this.robot.getFirmwareUpdateInfo().getState();
                if (!mIsOnLine || firmwareState_water == 2) {
                    //如果设备离线或者正在滑动界面
                    return;
                }
                int water = this.robot.getCleanSettings().getMopHumidity();
                if (water != bottomLayoutView.mWater) {
                    LogUtils.i(water + " : ++++++++++++++++水量+++++++++++++++++++ : " + bottomLayoutView.mWater);
                    if (Constants.isButtomOpen) {
                        if (bottomLayoutView.bun_time_water != null) {
                            bottomLayoutView.bun_time_water.cancel();//终止按钮倒计时
                        }
                        bottomLayoutView.recoverWaterBtn();
                        bottomLayoutView.setSuctionWater();
                    }
                }
                break;
            case Event.MESSAGE_TYPE_SUCTION_STATUS:
                //吸力
                if (!mIsOnLine) {
                    return;
                }
                LogUtils.i(" : ++++++++++++吸力+++++++++++++++1111+++++++++ : " + bottomLayoutView.mSuction);
                int firmwareState_suction = this.robot.getFirmwareUpdateInfo().getState();
                if (firmwareState_suction == 2) {
                    //如果设备离线或者正在滑动界面
                    return;
                }
                if (Constants.isButtomOpen) {
                    int suction = this.robot.getCleanSettings().getSuction();
                    if (suction != bottomLayoutView.mSuction) {
                        LogUtils.i(suction + " : ++++++++++++吸力++++++++++++++++++++++++ : " + bottomLayoutView.mSuction);
                        if (bottomLayoutView.bun_time_sucion != null) {
                            bottomLayoutView.bun_time_sucion.cancel();//终止按钮倒计时
                        }
                        bottomLayoutView.recoverSuctionBtn();
                        bottomLayoutView.setSuctionWater();
                    }
                }
                break;
            case Event.MSG_ROBOT_SETTINGS:
            case Event.MESSAGE_TYPE_TANK_DUSTBOX_STATUS:
                //设置（定制模式，吸力，水量,回洗，地毯增压）
                //X3使用，尘盒水箱状态 117 118
                if (Constants.isButtomOpen) {
                    bottomLayoutView.setSuctionWater();
                }
                break;
            case Event.MESSAGE_TYPE_CLEAN_MOP:
                //清洗拖布
                boolean cleanMop = this.robot.getCleanSettings().isCleanMop();
                if (cleanMop) {
                    mCbCleanMop.setText(getString(R.string.BS_CleanMop_Cancel));
                } else {
                    mCbCleanMop.setText(getString(R.string.BS_CleanMop_Start));
                }
                mCbCleanMop.setChecked(cleanMop);
                break;
//            case Event.MSG_ROBOT_STATE_POWER:
//                //电池电量
//                if (!mIsOnLine) {
//                    //如果设备离线或者正在滑动界面
//                    return;
//                }
//                int workState = this.robot.getRobotStatus().getWorkState();
//                int workMode = this.robot.getRobotStatus().getWorkMode();
//                LogUtils.i("电池电量 ======================== ");
//                chargingShow(workMode, workState);
//                break;
            case Event.MESSAGE_TYPE_FAULT_STATUS:
                //故障上报，当dp：28上报的比故障状态晚时
                if (!mIsOnLine) {
                    //如果设备离线或者正在滑动界面
                    return;
                }
                String error = robot.getRobotStatus().getError();
                if (error != null) {
                    if (!errorStr.equals(error)) {//临时存储，避免多次上报时，走多次
                        errorStr = error;
                        int firmwareState_fault = this.robot.getFirmwareUpdateInfo().getState();
                        if (firmwareState_fault != 2) {
                            LogUtils.i("清除故障  ==error : " + error);
                            if (error.equals("0") || error.equals("255")) {
                                activity.mMesListData.clear();//消息列表
                                activity.setFaultState("恢复正常", 0, "0000");
                                fault_error = 0;
                            } else {
                                String errMsgByCode = AppContext.getProductService().getFaultMsgByCode(activity, error);
                                LogUtils.i("动态故障  ==4444: " + errMsgByCode);
                                activity.setFaultState(errMsgByCode, 2, "111");
                                fault_error = 1;
                            }
                        }
                    }
                    int state = this.robot.getRobotStatus().getWorkState();
                    setFaultErrorLight(state, "故障");
                }
                break;

            case Event.MESSAGE_TYPE_GYRO_UPGRADE_PROGRESS:
                //N5机器升级过程中动态上报
                receiveFirmwareUpgradeStatus();//根据固件当前状态进行 UI布局显示
                break;
            case Event.MESSAGE_TYPE_DATA_FUNC:
                //x3系列机器升级过程中动态上报，这里要区分是固件过来的还是语言设置过来的
                String dataFunc = (String) event.getContent();
                try {
                    JSONObject jsonObject = new JSONObject(dataFunc);
                    if (!jsonObject.has("func")) {
                        return;
                    }
                    String func = jsonObject.getString("func");
                    if (!func.equals("upgrade")) {
                        return;
                    }
                    int status = jsonObject.getInt("status");
                    robot.getFirmwareUpdateInfo().setState(status);
                    receiveFirmwareUpgradeStatus();//根据固件当前状态进行 UI布局显示
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
//            case Event.MESSAGE_TYPE_CHECK_UPGRADE_STATE:
//                //动态 固件升级状态
//                if (!productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmwareChannel)) {
//                    int upgradeState = (int) event.getContent();
//                    LogUtils.i("动态 升级状态 ------" + upgradeState);
//                    if (upgradeState == 2) {
//                        int progress = this.robot.getFirmwareUpdateInfo().getProgress();
//                        LogUtils.i("动态 升级状态 progress------" + progress);
//                        if (AppContext.get().getDeviceList().size() > 0) {
//                            this.robot.getFirmwareUpdateInfo().setUpgradeStatus(3);
//                            this.robot.getFirmwareUpdateInfo().setProgress(progress);
//                        }
//                        int UpdateLayout_dynamic = mFirmwareUpdateLayout.getVisibility();//判断升级布局是否可见
//                        if (UpdateLayout_dynamic == 0) {
//                            //如果已经显示了升级布局，就不走多次了，避免重复上报
//                            return;
//
//                        }
//                        if (activity.firmware_dialog != null) {
//                            if (activity.firmware_dialog.isShowing()) {
//                                activity.firmware_dialog.dismiss();//关闭估计新版本弹框
//                            }
//                        }
//                        ViewUpgradeTips();//查看升级状态提示布局
//                        break;
//                    } else if (upgradeState == 7) {
//                        //完成升级
//                        this.robot.getFirmwareUpdateInfo().setUpgradeStatus(0);
//                        setRobotMessage(Constants.ITEM_POSITION);
//                    }
//                }
//                break;
            case Event.MESSAGE_TYPE_CHECK_NEW_VERSION:
                //检测估计版本
                if (event.isResult() && !robot.isShare()) {
                    String odlVersionNumber = robot.getFirmwareInfo().getCompileVerions();

                    FirmwareUpdateInfo firmwareUpdateInfo = (FirmwareUpdateInfo) event.getContent();
                    robot.getFirmwareUpdateInfo().setFileName(firmwareUpdateInfo.getFileName());
                    Constants.version = firmwareUpdateInfo.getNewVersion();//新版本
                    Constants.UpdateDesc = firmwareUpdateInfo.getDesc();
                    robot.getFirmwareUpdateInfo().setCurrentVersion(firmwareUpdateInfo.getCurrentVersion());
                    LogUtils.i("检测估计版本 返回  ------" + new Gson().toJson(firmwareUpdateInfo));
                    if (odlVersionNumber.equals(Constants.version)) {
                        //无新版本  手动进行版本号比较
                    }
                    int result = AppUtil.compareVersion(Constants.version, odlVersionNumber);
                    int status = 0;
                    if (result == 1) {
                        status = 1;
                    } else if (result == 0) {
                        status = 0;
                    }
                    robot.getFirmwareUpdateInfo().setUpgradeStatus(status);
                    if (productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmwareChannel)) {
                        int state_ = robot.getFirmwareUpdateInfo().getState();
                        LogUtils.i("检测估计版本 state_ ------" + state_);
                        if (state_ == 1 || state_ == 2 || state_ == 3) {
                            //下载中 安装中
                            status = 2;
                            robot.getFirmwareUpdateInfo().setUpgradeStatus(2);
                        }
                    }

                    robot.getFirmwareUpdateInfo().setVersion(Constants.version);
                    robot.getFirmwareUpdateInfo().setDesc(Constants.UpdateDesc);
                    robot.getFirmwareUpdateInfo().setCheck(true);
                    if (status == 0) {
                        //无新版本
                        mFirmwareUpdateLayout.setVisibility(View.GONE);
                    } else if (status == 1) {
                        int upgradeType = firmwareUpdateInfo.getUpgradeType();
                        LogUtils.i("检测估计版本 Type ------" + upgradeType);
                        mUpgradeDesc.setText(Constants.UpdateDesc);
                        String mContent = getString(R.string.MO_Firmware_New) + Constants.version
                                + getString(R.string.MO_Firmware_New_Tip);
                        //对话框
                        LogUtils.i(" : newVersionsHintDialog ------------555555555555-------------" + Constants.click_location);
                        if (Constants.click_location.equals("")) {
                            activity.newVersionsHintDialog(activity, mContent, getString(R.string.MO_Firmware_New),
                                    getString(R.string.U_NoUpdate), getString(R.string.U_Update), Constants.version, Constants.UpdateDesc);
                        }
                    } else if (status == 2) {
                        int progress = firmwareUpdateInfo.getProgress();
                        this.robot.getFirmwareUpdateInfo().setProgress(progress);
                        LogUtils.i("估计版本 升级中 进度 ------" + progress);
                        //升级中
                        if (activity.firmware_dialog != null) {
                            if (activity.firmware_dialog.isShowing()) {
                                activity.firmware_dialog.dismiss();//关闭估计新版本弹框
                            }
                        }
                        ViewUpgradeTips();//查看升级状态提示布局
                    }
                }
                break;
            case Event.MESSAGE_TYPE_UPGRADE_RESULT:
                LogUtils.i("固件版本更新成功 ------------------------------------------------------");
                if (event.isResult()) {
                    this.robot.getFirmwareUpdateInfo().setCheck(true);
                    this.robot.getFirmwareUpdateInfo().setUpgradeStatus(0);
                    //固件版本更新成功
                    mFirmwareUpdateLayout.setVisibility(View.GONE);
                    activity.setBottomUiState("close", true, "102");
                } else {
                    //  AppContext.get().getCurrentDevice().getFirmwareUpdateInfo().setProgress(0);//保存升级进度
                    LogUtils.i("系统升级失败 ------------------------------------------------------");
                    if (firmwareNumber < 1) {
                        firmwareNumber = 1;
                        setRobotMessage(Constants.ITEM_POSITION);
                    }
                }
                break;
            case Event.MESSAGE_TYPE_DEVICE_INFO_UPDATE:
                // 设备名称修改变化
                LogUtils.i(" : 设备名称修改变化::::::::::::::::::::::::::::::::::: " + event.getContent().toString());
                mTvEquipmentSeriesName.setText(event.getContent().toString());
                break;
        }
    }

    public void stateShow() {
        LogUtils.i(" :  stateShow ==：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：：: ");
        if (!mIsOnLine) {
            return;
        }
        int state = robot.getRobotStatus().getWorkState();
        int subState = robot.getRobotStatus().getSubState();
        int mode = robot.getRobotStatus().getWorkMode();

        stateTransform = robotStateTransform(state);

        LogUtils.i(mIsOnLine + " :  stateShow ==state: " + state + " : mode : " + mode);
        if (state == RobotStatus.STATE_DORMANT) {
            LogUtils.i("state ==5: ");
            //休眠 状态
            setRechargeUiShowManage(state, activity.getString(R.string.H_State_Sleep), true);
        } else if (state == RobotStatus.STATE_STANDBY) {
            LogUtils.i("state ==0: ");
            if (subState == RobotStatus.SUBSTATE_WORKING_POS_UNARRIVE) {
                //目标点不可达
                setRechargeUiShowManage(state, getString(R.string.device_state_msg_PosUnarriveState), true);
            } else {
                //待机 状态
                setRechargeUiShowManage(state, activity.getString(R.string.H_State_Stanby), true);
            }
        } else if (state == RobotStatus.STATE_WORKING) {
            if (subState == RobotStatus.SUBSTATE_NONE) {
                //子状态为空 说明是清扫中
                if (mode == RobotStatus.MODE_AUTO_CLEAN) {
                    LogUtils.i("state ==1: ");
                    //工作中 状态 全屋清扫
                    mWorkingStatus = activity.getString(R.string.U_AutoClean);
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Start);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                } else if (mode == RobotStatus.MODE_ROOM_CLEAN) {
                    //选区清扫
                    mWorkingStatus = activity.getString(R.string.U_RoomClean);
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Start);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                } else if (mode == RobotStatus.MODE_CUSTOM_CLEAN) {
                    //区域清扫/自定义清扫
                    mWorkingStatus = activity.getString(R.string.U_ZoneClean);
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Start);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                } else if (mode == RobotStatus.MODE_EDGE_CLEAN) {
                    //沿边清扫
                    mWorkingStatus = activity.getString(R.string.U_EdgeClean);
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Start);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                } else if (mode == RobotStatus.MODE_SPOT_CLEAN) {
                    //定点扫清扫
                    if (productConfig.optBoolean(ProductConfigConstants.isInxni)) {
                        mWorkingStatus = activity.getString(R.string.U_SpotClean);
                    } else {
                        mWorkingStatus = activity.getString(R.string.U_SpotClean);
                    }
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Start);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                } else if (mode == RobotStatus.MODE_RECHARGE) {
                    //回充中
                    mWorkingStatus = activity.getString(R.string.H_State_Recharge);
                    mSing = true;
                    mButStatus = activity.getString(R.string.H_Recharge_Pause);
                    mRechargeIcon = R.mipmap.pause_recharge_icon;
                    mCleanIcon = R.mipmap.start_clean;
                } else if (mode == RobotStatus.MODE_CONTROL) {
                    //遥控模式
                    mWorkingStatus = activity.getString(R.string.U_RemoteMode);
                    mSing = true;
                    mButStatus = activity.getString(R.string.H_Recharge_Pause);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.start_clean;
                }
            } else {
                //子状态不为空 说明显示子状态信息
                if (subState == RobotStatus.SUBSTATE_WORKING_POS_ARRIVED) {
                    //目标点已到达
                    mWorkingStatus = activity.getString(R.string.device_state_msg_PosArrivedState);
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Pause);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                } else if (subState == RobotStatus.SUBSTATE_WORKING_GOTO_POS) {
                    LogUtils.i("state ==18: ");
                    mWorkingStatus = activity.getString(R.string.device_state_msg_GotoPositionState);
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Pause);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                } else if (subState == RobotStatus.SUBSTATE_WORKING_REPOSITING) {
                    LogUtils.i("state ==22: ");
                    mWorkingStatus = activity.getString(R.string.H_State_Locate);
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Pause);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                } else if (subState == RobotStatus.SUBSTATE_WORKING_CREATINGMAP) {
                    LogUtils.i("state ==23: ");
                    mWorkingStatus = activity.getString(R.string.U_NewMap);
                    mSing = false;
                    mButStatus = activity.getString(R.string.H_Recharge_Pause);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                    mCleanIcon = R.mipmap.pause_clean_icon;
                }
            }
            if (productConfig.optBoolean(ProductConfigConstants.rechargeBaseStation)) {
                //ZW2X U3PRO机型需要把开始回充换成基站的
                mButStatus = activity.getString(R.string.BS_Btn);
                mRechargeIcon = R.mipmap.home_base_station_icon;
            }
            workingStatus(mode, state, mWorkingStatus, mSing, mButStatus, mRechargeIcon, mCleanIcon);
        } else if (state == RobotStatus.STATE_PAUSE) {
            LogUtils.i("state ==2: ");
            //暂停工作状态
            setRechargeUiShowManage(state, activity.getString(R.string.U_Pause), false);
        } else if (state == RobotStatus.STATE_CHARGING) {
            int battery = robot.getRobotStatus().getBattery();
            String bay = "";
            LogUtils.i(battery + " : state ==3: ");
            if (battery == 100) {
                //充电完成
                bay = activity.getResources().getString(R.string.H_State_FullCharge);
            } else {
                //充电中
                bay = activity.getResources().getString(R.string.H_State_Charging);
            }
            setRechargeUiShowManage(state, bay, true);
        } else if (state == RobotStatus.STATE_ERROR) {
            //故障状态 禁止
            String error = robot.getRobotStatus().getError();
            if (error != null) {
                String errMsgByCode = AppContext.getProductService().getFaultMsgByCode(activity, error);
                LogUtils.i("state ==4444: " + errMsgByCode);
                activity.setFaultState(errMsgByCode, 2, "2222");
            }

            setRechargeUiShowManage(state, activity.getResources().getString(R.string.H_State_Error), true);
        } else if (state == RobotStatus.STATE_DUST_COLLECTION) {
            //集尘
            LogUtils.i("state ==9: ");
            //显示设置中间显示的（状态，清扫时间，清扫面积）
            SetTextImageShow.setStateText(mTvSweepState, activity.getResources().getString(R.string.Collect_ing), mLLSweepState, mTvElseState, mRlMainStateBg, true, true);
            Drawable drawable = AppCompatResources.getDrawable(activity, R.mipmap.collect_dust_prohibit_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            bottomLayoutView.mTvMainRecharge.setCompoundDrawables(null, drawable, null, null);
            bottomLayoutView.mTvMainRecharge.setText(R.string.Finished_collecting_dust);
            bottomLayoutView.mTvMainRecharge.setTextColor(ContextCompat.getColor(activity, R.color.hint_gray));
            bottomLayoutView.mTvMainRecharge.setEnabled(false);//查看地图
            bottomLayoutView.mTvMainRecharge.setEnabled(false);
            bottomLayoutView.mMainCleanMotionButton.setClickable(false);//清扫按钮
            selfCleaningHintDialog("集尘");
            String message = robot.getRobotStatus().getMessage();//消息 dp:128
//            Log.d(TAG, "state ==9 坎坎坷坷扩 : " + message);
            setLookMapUiShowManage();
            if (message != null && !message.equals("0")) {
                judgeDustState(message);
            }
        } else if (state == RobotStatus.STATE_DUST_COLLECTION_PUBLIC) {
            LogUtils.i("state ==10: ");
            //X1机型只显示集尘状态
            setRechargeUiShowManage(state, activity.getResources().getString(R.string.Collect_ing), true);
        } else if (state == RobotStatus.STATE_DRYING_MOP) {
            LogUtils.i("state ==13: ");
            //拖布风干中
            mCbCleanMop.setEnabled(true);
            mCbCleanMop.setChecked(false);
            mCbCleanMop.setText(getString(R.string.BS_CleanMop_Start));
            if (productConfig.optBoolean(ProductConfigConstants.rechargeBaseStation)) {
                //烘干中
                setRechargeUiShowManage(state, activity.getResources().getString(R.string.H_State_Dry), true);
            } else {
                //风干中
                setRechargeUiShowManage(state, activity.getResources().getString(R.string.Drying_the_mop), true);
            }
        } else if (state == RobotStatus.STATE_CLEANING_MOP) {
            //清洗拖布中（隐藏这个开始/取消清洗按钮）
            LogUtils.i("state ==14: ");
            mCbCleanMop.setEnabled(true);
            selfCleaningHintDialog("清洗拖布中");
            setRechargeUiShowManage(state, activity.getResources().getString(R.string.device_state_msg_mop_cleaning), true);
        } else if (state == RobotStatus.STATE_GOTO_BS) {
            //返回基站中
            LogUtils.i("state ==17: ");
            mCbCleanMop.setChecked(true);
            mCbCleanMop.setText(getString(R.string.BS_CleanMop_Cancel));
            mCbCleanMop.setEnabled(false);//返回基站中 不可以取消
            if (productConfig.optBoolean(ProductConfigConstants.rechargeBaseStation)) {
                setRechargeUiShowManage(state, activity.getResources().getString(R.string.BS_SelfClean_Start), true);
            } else {
                setRechargeUiShowManage(state, activity.getResources().getString(R.string.back_base), true);
            }
        } else if (state == RobotStatus.STATE_WATER_INJECTION) {
            //水箱加水中
            selfCleaningHintDialog("水箱加水中");
            setRechargeUiShowManage(state, activity.getResources().getString(R.string.BS_In_Water), true);
        }
        //根据状态显示灯显 注水中
        chargingShow(mode, state);
    }

    /***
     * 根据机器型号，进行主界面 回充UI 显示
     */
    private void setRechargeUiShowManage(int state, String statusSescription, boolean sing) {
        if (productConfig.optBoolean(ProductConfigConstants.hasDustCollectingBarrel)) {
            if (state == RobotStatus.STATE_CHARGING) {
                bottomLayoutView.mTvMainRecharge.setTextColor(ContextCompat.getColor(activity, R.color.textview_color2));
                bottomLayoutView.mTvMainRecharge.setEnabled(true);
                bottomLayoutView.mMainCleanMotionButton.setClickable(true);//开始清扫按钮
                if (productConfig.optBoolean(ProductConfigConstants.rechargeBaseStation)) {
                    mButStatus = activity.getString(R.string.BS_Btn);
                    mRechargeIcon = R.mipmap.home_base_station_icon;
                } else {
                    mButStatus = activity.getResources().getString(R.string.Finished_collecting_dust);
                    mRechargeIcon = R.mipmap.collect_dust_icon;
                }
                mCleanIcon = R.mipmap.start_clean;
                LogUtils.i("setRechargeUiShowManage 444444444444444444444444    : ");
            } else {
                bottomLayoutView.mTvMainRecharge.setTextColor(ContextCompat.getColor(activity, R.color.textview_color2));
                bottomLayoutView.mTvMainRecharge.setEnabled(true);//充电时，解除 禁止点击开始回充
                bottomLayoutView.mMainCleanMotionButton.setClickable(true);//开始清扫按钮
                if (productConfig.optBoolean(ProductConfigConstants.rechargeBaseStation)) {
                    mButStatus = activity.getString(R.string.BS_Btn);
                    mRechargeIcon = R.mipmap.home_base_station_icon;
                } else {
                    mButStatus = activity.getResources().getString(R.string.H_Recharge_Start);
                    mRechargeIcon = R.mipmap.home_charge_invalid;
                }
                mCleanIcon = R.mipmap.start_clean;
            }
        } else {
            if (state == RobotStatus.STATE_CHARGING || state == RobotStatus.STATE_GOTO_BS ||
                    state == RobotStatus.STATE_CLEANING_MOP || state == RobotStatus.STATE_DRYING_MOP) {
                LogUtils.i("setRechargeUiShowManage 3333333333333333333333333    : ");
                mButStatus = activity.getResources().getString(R.string.H_Recharge_Start);
                mRechargeIcon = R.mipmap.home_charge_invalid_prohibit;
                mCleanIcon = R.mipmap.start_clean;
                //如果是充电状态，就禁止回充按钮
                bottomLayoutView.mTvMainRecharge.setTextColor(ContextCompat.getColor(activity, R.color.hint_gray));
                bottomLayoutView.mTvMainRecharge.setEnabled(false);//充电时，禁止点击开始回充
            } else {
                LogUtils.i("setRechargeUiShowManage 55555555555555555555555555555555    : " + statusSescription);
                mButStatus = activity.getResources().getString(R.string.H_Recharge_Start);
                mRechargeIcon = R.mipmap.home_charge_invalid;
                mCleanIcon = R.mipmap.start_clean;
                bottomLayoutView.mTvMainRecharge.setTextColor(ContextCompat.getColor(activity, R.color.textview_color2));
                bottomLayoutView.mTvMainRecharge.setEnabled(true);//充电时，解除 禁止点击开始回充
                bottomLayoutView.mMainCleanMotionButton.setClickable(true);//开始清扫按钮
            }
        }
        //显示设置中间显示的（状态，清扫时间，清扫面积）
        SetTextImageShow.setStateText(mTvSweepState, statusSescription, mLLSweepState, mTvElseState, mRlMainStateBg, sing, true);
        //清扫、回充状态切换显示（底部布局）
        Drawable drawable = AppCompatResources.getDrawable(activity, mRechargeIcon);
        SetTextImageShow.clean_Recharge_StateShow(bottomLayoutView.mTvMainRecharge, mButStatus,
                drawable, bottomLayoutView.mMainCleanMotionButton, mCleanIcon);
    }

    private void workingStatus(int mode, int state, String workingStatus, boolean sing, String buttonState, int rechargeIcon, int cleanIcon) {

        LogUtils.i(CurrentMode + " , " + mode + " : MODE workingStatus  STATE: " + CurrentState + " , " + state);
        if (CurrentMode != mode || CurrentState != state) {
            String mButtonStateStr = buttonState;
            LogUtils.i(mButtonStateStr + "  ： workingStatus is null : " + buttonState);
            bottomLayoutView.mTvMainRecharge.setTextColor(ContextCompat.getColor(activity, R.color.textview_color2));
            bottomLayoutView.mTvMainRecharge.setEnabled(true);//充电时，解除 禁止点击开始回充
            bottomLayoutView.mMainCleanMotionButton.setClickable(true);//开始清扫按钮
            bottomLayoutView.mTvMainRecharge.setText(activity.getResources().getString(R.string.H_Recharge_Start));

            SetTextImageShow.setStateText(mTvSweepState, workingStatus, mLLSweepState, mTvElseState, mRlMainStateBg, sing, true);
            //清扫、回充状态切换显示（底部布局）
            Drawable drawable = AppCompatResources.getDrawable(activity, rechargeIcon);
            SetTextImageShow.clean_Recharge_StateShow(bottomLayoutView.mTvMainRecharge, mButtonStateStr,
                    drawable, bottomLayoutView.mMainCleanMotionButton, cleanIcon);

            if (productConfig.optBoolean(ProductConfigConstants.hasWashMop)) {
                //zw11机器当从清洗中变成工作状态时要显示请洗拖布
                mCbCleanMop.setText(activity.getResources().getString(R.string.BS_CleanMop_Start));
                mCbCleanMop.setChecked(false);
                mCbCleanMop.setVisibility(View.VISIBLE);
            }

        }

    }

    private void chargingShow(int mode, int state) {
        //避免每次状态过来都进来
        int battery = robot.getRobotStatus().getBattery();
        mTvPower.setText(battery + "%");
        mBatteryView.setPower(battery, robot);
        LogUtils.i(Constants.bun_time_mode + " :  chargingShow-----------   : " + battery + " : " + mBattery);
        if (CurrentMode != mode || CurrentState != state || battery == 20 || battery == 19 || mBattery != battery) {
            Log.d(TAG, CurrentState + "隐藏  隐藏 隐藏 隐藏 隐藏 隐藏 隐藏: " + state + ": mode : " + mode);
            standbyShow(state);
            if (!Constants.bun_time_mode && (CurrentMode != mode || CurrentState != state)) {
                LogUtils.i(mode + " 隐藏  隐藏 隐藏 隐藏 隐藏 隐藏 隐藏----------gghhhh--------------------------------: " + state);
                //如果在倒计时中，上报状态不更改,TODO:在底部展开的情况下时有状态上报切换
                if (Constants.isButtomOpen) {
                    bottomLayoutView.selectMode();//动态更新上拉中模式是否选中
                }
            }
            CurrentState = state;
            CurrentMode = mode;
            mBattery = battery;
            if (battery != 100) {
                mBattery = 0;
            }
        }
    }

    private void standbyShow(int state) {
        //这里是只有u3pro有的弹框
        if (state != RobotStatus.STATE_WATER_INJECTION && state != RobotStatus.STATE_CLEANING_MOP && state != RobotStatus.STATE_DUST_COLLECTION) {
            if (AppContext.selfCleaningDialog != null && AppContext.selfCleaningDialog.isShowing()) {
                AppContext.selfCleaningDialog.dismiss();//基站状态弹框
            }
        }
        if (productConfig.optBoolean(ProductConfigConstants.hasWashMop)){
            if (state == 14) {
                //清洗拖布中
                mCbCleanMop.setVisibility(View.GONE);
            } else {
                mCbCleanMop.setVisibility(View.VISIBLE);
            }
        }
        setFaultErrorLight(state, "1111111");
        if (state == 3) {
            int battery = robot.getRobotStatus().getBattery();
            if (battery == 100) {
                //充电图标
                mIvChargringIcon.setVisibility(View.GONE);
            } else {
                //充电图标
                mIvChargringIcon.setVisibility(View.VISIBLE);
            }
        } else {
            //充电图标
            mIvChargringIcon.setVisibility(View.GONE);
        }
        if (state == RobotStatus.STATE_DORMANT) {
            mStateAnimation.setVisibility(View.INVISIBLE);//隐藏灯显
        }
        if (mIsOnLine && (state == RobotStatus.STATE_WORKING ||
                state == RobotStatus.STATE_GOTO_BS)) {
            //启动旋转动画
            AnimationtUtils.setRotateAnimation(mAnimateSideBrush, 500);
            if (productConfig.optBoolean(ProductConfigConstants.rightSideBrush)) {
                //启动旋转动画 右侧边刷
                AnimationtUtils.setRotateAnimationRight(mAnimateSideBrushRight, 500);
            }
        } else {
            //停止旋转动画
            AnimationtUtils.stopRotateAnimation();
            if (productConfig.optBoolean(ProductConfigConstants.rightSideBrush)) {
                //停止旋转动画 右侧边刷
                AnimationtUtils.stopRotateAnimationRight();
            }
        }
    }

    private void setFaultErrorLight(int state, String tag) {
        LogUtils.i(state + "-------setFaultErrorLight ----- " + fault_error + " , tag :" + tag);
        if (state != 4 && fault_error == 0) {
            for (int i = 0; i < activity.mMesListData.size(); i++) {
                if (activity.mMesListData.get(i).getType() == 2) {
                    activity.mMesListData.remove(i);
                    activity.messageListIsShow(activity.mMesListData);
                }
            }
            LightAnimationUtils.setLight(mStateAnimation, robot, false);
        } else {
            LightAnimationUtils.setLight(mStateAnimation, robot, true);
        }
    }

    private void offLineState() {
        if (bottomLayoutView.bun_time_water != null) {
            bottomLayoutView.bun_time_water.cancel();//终止按钮倒计时
        }
        if (bottomLayoutView.bun_time_sucion != null) {
            bottomLayoutView.bun_time_sucion.cancel();//终止按钮倒计时
        }
        //这里是只有u3pro有的弹框
        if (AppContext.selfCleaningDialog != null && AppContext.selfCleaningDialog.isShowing()) {
            AppContext.selfCleaningDialog.dismiss();//基站状态弹框
        }
        LogUtils.i("离线了-------------------------------------------------------------- ");
        if (activity.firmware_dialog != null) {
            activity.firmware_dialog.dismiss();
        }
        //如果机器离线，一切的设备信息都不显示
        activity.setBottomUiState("close", false, "99");

        // AppContext.get().setInterfaceIsSlide(false);
        mOfflineLayout.setVisibility(View.VISIBLE);
        SetTextImageShow.setStateText(mTvSweepState, activity.getResources().getString(R.string.H_State_Offline), mLLSweepState, mTvElseState, mRlMainStateBg, true, false);
        activity.mMesListData.clear();
        activity.binding.mainMesList.setVisibility(View.GONE);//消息列表
        //隐藏电量布局
        mRlFragmentBattery.setVisibility(View.GONE);
        //隐藏灯显
        mStateAnimation.clearAnimation();
        mStateAnimation.setVisibility(View.INVISIBLE);
        //隐藏固件升级布局
        mFirmwareUpdateLayout.setVisibility(View.GONE);
        //隐藏清洗拖布中
        mCbCleanMop.setVisibility(View.GONE);
        //隐藏充电图标
        mIvChargringIcon.setVisibility(View.GONE);
        //停止旋转动画
        AnimationtUtils.stopRotateAnimation();
        if (productConfig.optBoolean(ProductConfigConstants.rightSideBrush)) {
            //停止旋转动画 右侧边刷
            AnimationtUtils.stopRotateAnimationRight();
        }
    }

    /***
     * 根据机器型号，进行主界面 查看地图UI 显示
     */
    private void setLookMapUiShowManage() {
        if (productConfig.optBoolean(ProductConfigConstants.hasMap)) {
            Drawable drawable = AppCompatResources.getDrawable(activity, R.mipmap.look_map_icon);
            if (drawable != null) {
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                bottomLayoutView.mMainCheckMap.setCompoundDrawables(null, drawable, null, null);
                bottomLayoutView.mMainCheckMap.setTextColor(ContextCompat.getColor(activity, R.color.textview_color2));
            }

            bottomLayoutView.mMainCheckMap.setEnabled(true);//地图管理设置为可点
            bottomLayoutView.mTvPreferences.setVisibility(View.GONE);//偏好设置不可见
            bottomLayoutView.mMainCheckMap.setVisibility(View.VISIBLE);//地图管理

            if (productConfig.optInt(ProductConfigConstants.product_type) == ProductConfigConstants.PRODUCT_TYPE_GYRO) {
                bottomLayoutView.mMainCheckMap.setText(activity.getResources().getString(R.string.check_map)); //陀螺仪机器 无法操作地图 只能查看地图
            } else {
                bottomLayoutView.mMainCheckMap.setText(activity.getResources().getString(R.string.H_Map_Manage));//显示地图管理
            }
        } else {
            bottomLayoutView.mIvMapManagerNotRead.setVisibility(View.GONE);//去掉小红点

            if (productConfig.optBoolean(ProductConfigConstants.isInxni)) {
                //GD的查看地图按钮替换为偏好设置按钮  简直是翻怪
                bottomLayoutView.mMainCheckMap.setVisibility(View.GONE);//地图管理
                bottomLayoutView.mTvPreferences.setVisibility(View.VISIBLE);//偏好设置

                Drawable drawable = AppCompatResources.getDrawable(activity, R.mipmap.preferences_icon);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                bottomLayoutView.mTvPreferences.setCompoundDrawables(null, drawable, null, null);
            } else {
                //RS01 没有地图 但是要显示查看地图按钮 但是无法点击 灰色
                Drawable drawable = AppCompatResources.getDrawable(activity, R.mipmap.look_map_look_map_icon_icon);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                bottomLayoutView.mMainCheckMap.setCompoundDrawables(null, drawable, null, null);
                bottomLayoutView.mMainCheckMap.setText(activity.getResources().getString(R.string.check_map));//显示查看地图
                bottomLayoutView.mMainCheckMap.setTextColor(ContextCompat.getColor(activity, R.color.hint_gray));
                bottomLayoutView.mMainCheckMap.setEnabled(false);//地图管理设置为禁点
                bottomLayoutView.mTvPreferences.setVisibility(View.GONE);//偏好设置
                bottomLayoutView.mMainCheckMap.setVisibility(View.VISIBLE);//地图管理
            }
        }
    }

    /**
     * 判断当前集尘桶的状态
     */
    private void judgeDustState(String mes) {

        if (!dustSingState.equals(mes)) {
            dustSingState = mes;
            String dustCollect = "";
            if (mes.equals("14") || mes.equals("15") || mes.equals("19") ||
                    mes.equals("18") || mes.equals("20") || mes.equals("21")) {
                //添加进入该界面标记
                if (mes.equals("14")) {
                    dustCollect = getString(R.string.dust_bag_full);
                } else if (mes.equals("15")) {
                    dustCollect = getString(R.string.no_dust_bags);
                } else if (mes.equals("19")) {
                    dustCollect = getString(R.string.Frequent_dust);
                } else if (mes.equals("20")) {
                    dustCollect = getString(R.string.Finished_collecting_dust);
                } else if (mes.equals("21")) {
                    dustCollect = getString(R.string.Dust_collecting_duct_blocked);
                }
                dustCollectHintDialog("", dustCollect);
            }
        }
    }

    private void dustCollectHintDialog(String dialogTitle, String content) {

        if (dialog == null) {
            dialog = new Dialog(activity);
        }
        dialog.setContentView(R.layout.hint_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);

        TextView mBtnCenteredConfirm = dialog.findViewById(R.id.btn_hintConfirm);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogHintTitle);
        TextView mTvDialogContent = dialog.findViewById(R.id.tv_hint_content);
        mTvDialogTitle.setText(dialogTitle);
        mTvDialogContent.setText(content);
        mBtnCenteredConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    private void selfCleaningHintDialog(String tag) {
        LogUtils.i(AppContext.selfCleaningDialog + " selfCleaningHintDialog ------------------------- " + tag);
        if (AppContext.selfCleaningDialog == null) {
            AppContext.selfCleaningDialog = new Dialog(activity);
        }
        LogUtils.i(" selfCleaningHintDialog ----------vvvvvvvvvv--------------- " + AppContext.selfCleaningDialog);
        AppContext.selfCleaningDialog.setContentView(R.layout.self_cleaning_hint_dialog);
        AppContext.selfCleaningDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        AppContext.selfCleaningDialog.setCanceledOnTouchOutside(false);

        TextView mTvCloseDialog = AppContext.selfCleaningDialog.findViewById(R.id.tv_closeDialog);
        mTvCloseDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppContext.selfCleaningDialog.dismiss();
            }
        });
        AppContext.selfCleaningDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
        LogUtils.i(stateTransform + "  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>---- " + AppContext.selfCleaningDialog.isShowing());
        if (!AppContext.selfCleaningDialog.isShowing() && stateTransform) {
            LogUtils.i("++++++++++++++++++++++++++ ");
            AppContext.selfCleaningDialog.show();
        }
    }

    public void ViewUpgradeTips() {
        activity.mMesListData.clear();
        activity.binding.mainMesList.setVisibility(View.GONE);//消息列表
        mRlFragmentBattery.setVisibility(View.GONE);//隐藏电量
        //正在升级中
        SetTextImageShow.setStateText(mTvSweepState, activity.getResources().getString(R.string.O_Update), mLLSweepState, mTvElseState, mRlMainStateBg, true, false);
        mFirmwareUpdateLayout.setVisibility(View.VISIBLE);
        mUpgradeDesc.setText(R.string.O_Update_Tip);
        mUpdate_Now.setText(R.string.O_Update_Btn);
        activity.setBottomUiState("close", false, "100");
        LogUtils.i("动态 升级状态 --4444444444444444444444444444444----");
    }

    private void receiveFirmwareUpgradeStatus() {
        int state = robot.getFirmwareUpdateInfo().getState();
        if (state == 0) {
            //没有升级
            this.robot.getFirmwareUpdateInfo().setUpgradeStatus(0);
            setRobotMessage(Constants.ITEM_POSITION);
        } else {
            int UpdateLayout_dynamic = mFirmwareUpdateLayout.getVisibility();//判断升级布局是否可见
            if (UpdateLayout_dynamic == 0) {
                //如果已经显示了升级布局，就不走多次了，避免重复上报
                return;
            }
            if (activity.firmware_dialog != null) {
                if (activity.firmware_dialog.isShowing()) {
                    activity.firmware_dialog.dismiss();//关闭估计新版本弹框
                }
            }
            ViewUpgradeTips();//查看升级状态提示布局
        }
    }

//    private void forceUpgradeTips() {
//        activity.setBottomUiState("close", false, "101");
////        if (currentItem > AppContext.get().getDeviceList().size()) {
////            return;
////        }
//        String desc = AppContext.get().getDeviceList().get(currentItem).getFirmwareUpdateInfo().getDesc();
//        if (desc != null) {
//            mUpgradeDesc.setText(desc);
//        }
//        // LogUtils.i("检测估计版本 Desc ------" + desc);
//        activity.mMesListData.clear();
//        activity.binding.mainMesList.setVisibility(View.GONE);//消息列表
//        mRlFragmentBattery.setVisibility(View.GONE);//隐藏电量
//        mOfflineLayout.setVisibility(View.GONE);
//        mFirmwareUpdateLayout.setVisibility(View.VISIBLE);
//    }

    private void setGuideInterface(String tag) {
        //判断是否是第一次安装程序(给出指引界面)
        boolean value1 = SharedPrefsUtil.getValue(activity, "isGuide", "isGuide", false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                LogUtils.i(tag + " : 指引界面 ------" + value1);
                if (!value1) {
                    int[] location = new int[2];
                    while (true) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ivSwitchRobotIcon.getLocationOnScreen(location);//得到相对当前控件的坐标位置
                        LogUtils.i(" : BaseStationFragment======= ======== location : " + location[0] + " , " + location[1]);
                        if (location[1] != 0) {
                            break;
                        }
                    }
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SharedPrefsUtil.putValue(activity, "isGuide", "isGuide", true);
                            guideDialog = new Dialog(activity);
                            guideDialog.setContentView(R.layout.main_guide_dialog);
                            guideDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                            guideDialog.setCanceledOnTouchOutside(false);
                            //设置全屏
                            guideDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

                            mainGuideLayout01 = guideDialog.findViewById(R.id.main_guide_layout01);
                            mainGuideLayout02 = guideDialog.findViewById(R.id.main_guide_layout02);
                            mainGuideLayout03 = guideDialog.findViewById(R.id.main_guide_layout03);
                            mainGuideLayout04 = guideDialog.findViewById(R.id.main_guide_layout04);

                            int barHeight = getStatusBarHeight(activity);
                            Log.d(TAG, "BaseStation Main======= ======== location :" + location[1]);
                            ivSwitchRobotIcon.getLocationOnScreen(location);//得到相对当前控件的坐标位置
                            mainGuideLayout04.setY(location[1] - barHeight);
                            mainGuideLayout01.setOnClickListener(activity);
                            mainGuideLayout02.setOnClickListener(activity);
                            mainGuideLayout03.setOnClickListener(activity);
                            mainGuideLayout04.setOnClickListener(activity);
                            guideDialog.show();
                        }
                    });
                }
            }
        }).start();

    }


    private boolean robotStateTransform(int currentState) {
        //这个方法是限制注水中 清扫拖布中 集尘中弹框显示的（如果已经显示过一次关闭了再来该状态就不再显示）
        int saveState = robot.getSaveState();
        if (saveState == -1) {
            robot.setSaveState(currentState);
            return true;
        } else {
            if (currentState == saveState) {
                return false;
            } else {
                robot.setSaveState(currentState);
                return true;
            }
        }
    }

    private int getStatusBarHeight(Activity activity) {
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return activity.getResources().getDimensionPixelSize(resourceId);
        }
        return 150;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getY() - e2.getY() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            if (!bottomLayoutView.mCbMainBottomUnfold.isChecked()) {
                // 向上手势
                activity.setBottomUiState("open", false, "open 222");
                bottomLayoutView.mCbMainBottomUnfold.setChecked(true);
            }
        } else if (e2.getY() - e1.getY() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            if (bottomLayoutView.mCbMainBottomUnfold.isChecked()) {
                if (bottomLayoutView.bun_time_water != null) {
                    bottomLayoutView.bun_time_water.cancel(); //点击吸力水量 开始倒计时终止
                    bottomLayoutView.recoverWaterBtn();//恢复吸力水量 按钮的状态
                }
                if (bottomLayoutView.bun_time_sucion != null) {
                    bottomLayoutView.bun_time_sucion.cancel(); //点击吸力水量 开始倒计时终止
                    bottomLayoutView.recoverSuctionBtn();//恢复吸力水量 按钮的状态
                }
                // 向下手势
                activity.setBottomUiState("close", true, "444");
                bottomLayoutView.mCbMainBottomUnfold.setChecked(false);
            }
        }
        return true;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

}
